﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Data;
using System.Linq;
using System.Diagnostics;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.DataSourcesGDB;
using PlanningGIS.DataConvert.model;
using PlanningGIS.Framework;
using PlanningGIS.Framework.Controls;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.Win.Controls;
using PlanningGIS.Util.Collections;
using PlanningGIS.Util.Convertor;
using PlanningGIS.ArcGIS;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Util.Win32;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Util.Log;
using PlanningGIS.MapSheet;
using PlanningGIS.Framework.Config;
using PlanningGIS.Util.Management;
using ESRI.ArcGIS.SystemUI;
using PlanningGIS.Util;
using PlanningGIS.MetaData;

namespace PlanningGIS.DataConvert.form
{
    /// <summary>
    /// 将数据导出到标准的dwg格式中
    /// </summary>
    public partial class FrmExportDwg : Office2007Form
    {        
        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmExportDwg()
        {
            InitializeComponent();            
        }

        /// <summary>
        /// 地图关联对象
        /// </summary>
        private IHookHelper _HookHelper = null;

        /// <summary>
        /// 地图关联对象
        /// </summary>
        public object Hook
        {
            set
            {
                _HookHelper = new HookHelper();
                _HookHelper.Hook = value;
            }
        }

        /// <summary>
        /// 导出操作
        /// </summary>
        private ExportCAD _Export = null;

        /// <summary>
        /// 绘制工具构建对象
        /// </summary>
        private ToolCreator _ToolCreator = null;

        /// <summary>
        /// 结合表选择构建对象
        /// </summary>
        private SheetCreator _SheetCreator = null;

        /// <summary>
        /// 加载窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataExport_Load(object sender, EventArgs e)
        {
            Init();                   
        }

        /// <summary>
        /// 初始化对象
        /// </summary>
        private void Init()
        {
            dtimDate.Value = DateTime.Now;
            _SheetCreator = new SheetCreator(spgrdSheet);
            _SheetCreator.Hook = _HookHelper.Hook;
            _SheetCreator.IsToMap = true;
            List<ValueName> btns = new List<ValueName>()
            {
                new ValueName(){Value="ToolDrawRectangle",Name="绘制矩形"},
                new ValueName(){Value="ToolDrawPolygon",Name="绘制多边形"},
                new ValueName(){Value="ToolDrawCircle",Name="绘制圆"},
                new ValueName(){Value="ToolDrawLine",Name="绘制线"}
            };
            _ToolCreator = new ToolCreator(btnDrawExtent, _HookHelper.Hook);
            _ToolCreator.HideForm = true;
            _ToolCreator.Create(btns, true);
            _ToolCreator.DrawFinished += OnDrawFinished;
            regionTree.Hook = _HookHelper.Hook;
            if (JHBHelper.ScaleValues != null)
            {
                foreach (int scale in JHBHelper.ScaleValues)
                {
                    this.cmbScale.Items.Add(scale.ToString());
                }
            }
            if (cmbScale.Items.Count > 0)
            {
                this.cmbScale.SelectedIndex = 0;
            }
            layersTree1.FeatureType = zjgisFeatureType.Vector;
            layersTree1.OnCreate(_HookHelper.Hook);
        }

        /// <summary>
        /// 绘制完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnDrawFinished(object sender, DrawArgs e)
        {
            if (sptbctlGeo.SelectedTab == sptbitmRegion)
                regionTree.SelectRegion(e.Geometry, e.Shift);
            else
                _SheetCreator.SelectRegion(e.Geometry, e.Shift);
        }

        /// <summary>
        /// 元数据类型选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void swtbtnMetaType_ValueChanged(object sender, EventArgs e)
        {
            txtUnit.Enabled = swtbtnMetaType.Value;
            txtJCY.Enabled = swtbtnMetaType.Value;
            txtCTY.Enabled = swtbtnMetaType.Value;
            txtCHY.Enabled = swtbtnMetaType.Value;
            dtimDate.Enabled = swtbtnMetaType.Value;
        }

        /// <summary>
        /// 比例尺选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbScale_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(cmbScale.Text)) return;
            if (_SheetCreator == null) return;
            _SheetCreator.ScaleValue = int.Parse(cmbScale.Text);
        }

        /// <summary>
        /// 选择保存路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (chkSplit.Checked)
            {
                if (folderBrowserDialog.ShowDialog() != DialogResult.OK) return;
                txtExportPath.Text = folderBrowserDialog.SelectedPath;
            }
            else
            {                
                if (saveFileExport.ShowDialog() != DialogResult.OK) return;
                txtExportPath.Text = saveFileExport.FileName;
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (!InitParam())
            {
                _Export = null;
                return;
            }
            FrameworkHelper.ShowLogPanel();
            this.Cursor = Cursors.WaitCursor;
            _Export.ProgressAll = new Progressor() { ProgressBar = progressBarAll };
            _Export.ProgressSub = new Progressor() { ProgressBar = progressBarSub };
            _Export.Export(chkSplit.Checked);
            this.Cursor = Cursors.Default;
            MsgHelper.ShowWarningMsgbox("Dwg已导出完成，请查看日志信息。");
        }

        /// <summary>
        /// 初始化界面参数信息
        /// </summary>
        /// <returns></returns>
        private bool InitParam()
        {
            if (string.IsNullOrWhiteSpace(txtExportPath.Text))
            {
                MsgHelper.ShowInfomationMsgbox("请选择导出路径！");
                return false;
            }
            _Export = new ExportCAD();
            _Export.FullName = txtExportPath.Text;
            if (sptbctlData.SelectedTab == sptbitmAddData) _Export.FeatureClasses = ctlDataSetList1.Datasets;
            else _Export.FeatureClasses = layersTree1.GetSelectLayers<IFeatureClass>();
            if (_Export.FeatureClasses == null || _Export.FeatureClasses.Count == 0)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择要导出的图层！");
                return false;
            }
            //_Export.Scale = swtbtnExpType.Value ? int.Parse(cmbScale.Text) : _HookHelper.FocusMap.MapScale;
            _Export.Scale = int.Parse(cmbScale.Text);//暂时只支持标准比例尺的导出
            if (sptbctlGeo.SelectedTab == sptbitmPoly) _Export.ClipExtent = _ToolCreator.Geometry;
            else if (sptbctlGeo.SelectedTab == sptbitmRegion)
                _Export.ClipExtent = regionTree.SelectedGeometry;
            if (chkSplit.Checked)
            {
                if (sptbctlGeo.SelectedTab == sptbitmSheet)
                    _Export.Sheets = _SheetCreator.CheckedSheets;
                else
                    _Export.Sheets = JHBHelper.GetSheetByGeometry(_Export.ClipExtent, (int)_Export.Scale);
                if (_Export.Sheets == null || _Export.Sheets.Count == 0)
                {
                    MsgHelper.ShowErrorMsgbox(this, "所选的范围内不存在相应的图幅，可能是图幅结合表不存在或超出了数据范围");
                    return false;
                }
            }
            else
            {
                if (sptbctlGeo.SelectedTab == sptbitmSheet)
                    _Export.ClipExtent = _SheetCreator.GetSelectGeometry();
            }
            _Export.IsClip = chkClip.Checked;
            _Export.HasMeta = epdpnlMeta.Expanded;
            _Export.CustomMeta = swtbtnMetaType.Value;
            _Export.IsOverlap = chkOverlap.Checked;
            _Export.HasTK = true;
            if (swtbtnMetaType.Value)
            {
                _Export.MetaValues = new Dictionary<string, string>();
                _Export.MetaValues.Add(MetaHelper.Key_CZDW, txtUnit.Text);
                _Export.MetaValues.Add(MetaHelper.Key_CZSJ, dtimDate.Value.ToString("yyyy-MM-dd"));
                _Export.MetaValues.Add(MetaHelper.Key_HTY, txtCHY.Text);
                _Export.MetaValues.Add(MetaHelper.Key_CLY, txtCTY.Text);
                _Export.MetaValues.Add(MetaHelper.Key_JCY, txtJCY.Text);
            }
            return true;
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 终止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdCancel_Click(object sender, EventArgs e)
        {
            if (_Export != null)
            {
                _Export.Stop();
                Application.DoEvents();
            }
        }
        
        /// <summary>
        /// 关闭窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataExport_FormClosing(object sender, FormClosingEventArgs e)
        {
            cmdCancel_Click(null, null);
            if (_ToolCreator != null) _ToolCreator.Clear();
            if (_SheetCreator != null) _SheetCreator.ClearElement();
            regionTree.Clear();
        }


    }
}
